using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Diagnostics;

namespace Andrewl.XnaHelpers.IO
{
    public static class _Xml
    {
        //XML serializer so we can serialize and deserialize objects
        public static XmlSerializer serializer;
        //StreamWriter so we can write our xml file
        public static StreamWriter fileWriter;
        //StreamReader so we can read our xml file
        public static StreamReader fileReader;
        //Our Xml reader
        public static XmlReader reader;

        /// <summary>
        /// Serialize the passed object to the path
        /// </summary>
        /// <typeparam name="T">The Type of object to serialize</typeparam>
        /// <param name="path">Path to write our file to MUST include the \ at the end</param>
        /// <param name="fileName">The name of our xml file do NOT include the '.xml' extension</param>
        /// <param name="obj">The object to serialize</param>
        public static void Serialize<T>(string path, string fileName, T obj)
        {
            fileWriter = new StreamWriter(path+fileName);
            serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(fileWriter, (T)obj);
            fileWriter.Close();
        }

        public static void Serialize<T>(string path, T obj)
        {
            fileWriter = new StreamWriter(path);
            serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(fileWriter, (T)obj);
            fileWriter.Close();
        }
        /// <summary>
        /// Deserialize the passed object at the specified path the path MUST include the filename and the file extension
        /// </summary>
        /// <typeparam name="T">The type to deserialize to</typeparam>
        /// <param name="path">Path has to include the filename and the file extensions</param>
        /// <returns></returns>
        public static T Deserialize<T>(string path)
        {
            fileReader = new StreamReader(path);
            serializer = new XmlSerializer(typeof(T));
            T returnVar = (T)serializer.Deserialize(fileReader);
            fileReader.Close();
            return returnVar;
        }

        public static bool CanDeserialize<T>(string path)
        {
            fileReader = new StreamReader(path);
            reader = new XmlTextReader(fileReader);
            serializer = new XmlSerializer(typeof(T));
            if (serializer.CanDeserialize(reader))
            {
               fileReader.Dispose();
               reader.Close();
               return true;
            }
            else
            {
                fileReader.Dispose();
                reader.Close();
                return false;
            }
        }
    }
}